package mybatis.proxy;

import mybatis.cfg.Configuration;
import mybatis.cfg.Mapper;
import top.jybill.domain.User;
import utils.Executor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

public class MapperProxy implements InvocationHandler {
  private Map<String, Mapper> mappers;
  private Connection conn;

  public MapperProxy(Map<String, Mapper> mappers, Connection conn) {
    this.mappers = mappers;
    this.conn = conn;
  }

  /**
   * 动态代理处理函数
   * @param proxy
   * @param method
   * @param args
   * @return
   * @throws Throwable
   */
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String metgodName = method.getName(); // 获取方法名
    String className = method.getDeclaringClass().getName();// 获取该方法的全类名
    String key = className + "." + metgodName; // map的Key 查找对应的Mapper对象
    Mapper mapper = mappers.get(key);
//    System.out.println(mapper);

    if (mapper == null) {
      throw new IllegalAccessException("参数错误");
    }
    return new Executor().selectList(mapper, conn);
  }
}
